package com.atguigu.gmall.mq.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 自定义应答实现类
 *
 *      接收交换机应答
 *      接收对称的应答
 */
//@Component//springIOC容器中
public class MQProducerAckConfig1 implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnCallback {

    @Resource
    private RabbitTemplate rabbitTemplate;

    //实现 “包名+接口名”，使接口与当前类有关系
    //构造器执行，就执行init方法
    @PostConstruct
    public void init(){
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
    }


    //交换机应答
    //应答时机：成功、失败 均应答
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            System.out.println("成功应答："+ cause);
        }else {
            System.out.println("失败应答："+cause);
            //重新发送消息
        }
    }

    //队列应答
    //应答时机：失败
    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        //重新发送
        System.out.println("message:"+new String(message.getBody())+"replyCode:"+replyCode+"replyText:"+replyText+"exchange:"+exchange+"routingKey:"+routingKey);
    }
}
